package com.song.mall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.song.common.constant.AuthServerConstant;
import com.song.common.exception.BizCodeEnume;
import com.song.common.to.MemberTO;
import com.song.common.utils.R;
import com.song.mall.auth.feign.ThirdPartyFeignService;
import com.song.mall.auth.feign.MemberFeignService;
import com.song.mall.auth.vo.UserLoginVo;
import com.song.mall.auth.vo.UserRegistVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 宋超
 * HP - the login name of the current user.
 * 2021/10/3 - the current system date.
 * 9:59 - the current system time.
 */
@Controller
public class LoginController {

    @Autowired
    ThirdPartyFeignService thirdPartyFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;


    @Autowired
    MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone){

        //TODO 1、接口防刷
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)){
            long l = Long.parseLong(redisCode.split("_")[1]);
            if(System.currentTimeMillis() - l < 600000){
                //60秒内不能再发
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(),BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        //验证码再次检验 redis 存key:手机号
        String code = UUID.randomUUID().toString().substring(0, 5);
        String substring = UUID.randomUUID().toString().substring(0,5)+"_"+System.currentTimeMillis();

        //redis缓存验证码 ，防止同一个手机在60秒内 重复 发送验证码
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,substring,10, TimeUnit.MINUTES);

        thirdPartyFeignService.sendCode(phone,code);
        return R.ok();
    }


    /**
     * 注册的控制器
     * RedirectAttributes 模拟重定向携带数据
     *  其原理：
     *      利用session原理，将数据放在session中，然后重定向到页面之后，再从session中取出来
     *      跳到下一个页面，然后取出数据以后，session里面的数据就会删掉，
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes redirectAttributes){
        if (result.hasErrors()){ //如果校验出错
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField,FieldError::getDefaultMessage));
            //存放错误消息，让前端感知并获取错误信息
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.mall.com/reg.html";//注册页
        }
        //1、校验验证码，从页面提交过来的验证码
        String code = vo.getCode();
        //获取到redis存的验证码
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (!StringUtils.isEmpty(s)){ //redis里面存了这个手机号对应的验证码
            //,验证码正确,就进行截串，拿到第一个数据然后进行对比
            if (code.equals(s.split("_")[0])){
                //验证码通过以后，还必须要删除验证码,因为这样下次若还带着之前的验证码过来，就会验证失败
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                //验证码通过，  如果上面校验并无出错，就进行注册 ，调用远程服务gulimall-member进行注册
                R r = memberFeignService.regist(vo);
                if (r.getCode() == 0){ //成功就返回登陆页
                    return "redirect:http://auth.mall.com/login.html";
                }else { //失败就返回注册页,并且显示错误消息
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg",r.getData("msg ",new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.mall.com/reg.html";//注册页
                }
            }else { //验证不通过
                Map<String, String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                //存放错误消息，让前端感知并获取错误信息
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.mall.com/reg.html";//注册页
            }
        }else {  //redis存的验证码已过期
            Map<String, String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            //存放错误消息，让前端感知并获取错误信息
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.mall.com/reg.html";//注册页
        }
    }


    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.SESSION_ATTR_NAME);
        if (attribute==null){
            //没登录
            return "login";
        }else {
            return "redirect:http://mall.com";
        }

    }

    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes,HttpSession httpSession){

        //远程登录
        R login = memberFeignService.login(vo);

        if (login.getCode()==0){
            //成功
            MemberTO data = login.getData("data", new TypeReference<MemberTO>() {
            });
            //放到session中
            httpSession.setAttribute(AuthServerConstant.SESSION_ATTR_NAME,data);
            return "redirect:http://mall.com";
        }else{
            Map<String,Object> map = new HashMap<>();
            map.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",map);
            return "redirect:http://auth.mall.com/login.html";
        }

    }
}
